package other.xsy.pms;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.rkhd.platform.sdk.ScheduleJob;
import com.rkhd.platform.sdk.data.model.*;
import com.rkhd.platform.sdk.exception.*;
import com.rkhd.platform.sdk.log.Logger;
import com.rkhd.platform.sdk.log.LoggerFactory;
import com.rkhd.platform.sdk.param.ScheduleJobParam;
import com.rkhd.platform.sdk.service.FutureTaskService;
import com.rkhd.platform.sdk.service.XoqlService;
import com.rkhd.platform.sdk.task.FutureTask;
import org.apache.commons.lang.StringUtils;
import other.xsy.pms.utils.*;

import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description: 同步PMS概算信息到业务机会
 * @Author: 黎炎松
 * @Date: 2024/10/26 14:23
 */
public class SyncPmsBudgetToOpt implements ScheduleJob, FutureTask {
    private static HCXObjectService hcxObjectService = new HCXObjectService();
    private static XoqlService xoqlService = XoqlService.instance();
    private static final Logger LOGGER = LoggerFactory.getLogger();
    private static String LOGGER_MSG = "同步PMS概算信息到业务机会 ==> ";

    /**
     * 定时任务触发
     * @param scheduleJobParam
     */
    @Override
    public void execute(ScheduleJobParam scheduleJobParam) {
        LOGGER.debug(LOGGER_MSG + " 开始");
        try {
            String messageId = FutureTaskService.instance().addFutureTask(getClass(), "");
            LOGGER.info(LOGGER_MSG + "异步ID:" + messageId);
        } catch (Exception e) {
            LOGGER.error(LOGGER_MSG + " ----- 发生异常：" + e.getMessage());
        }
    }

    /**
     * 异常任务执行
     * @param s
     * @throws ScriptBusinessException
     */
    @Override
    public void execute(String s) throws ScriptBusinessException {
        syncPmsBudget(2);
    }

    public static void main(String[] args) throws IOException {
        HCXObjectService.isLocal = true;
        SyncPmsBudgetToOpt syncPmsBudgetToOpt = new SyncPmsBudgetToOpt();
        //syncPmsBudgetToOpt.syncPmsBudget(2);

        JSONArray flowStatusPicks = ComUtils.getGlobalPicks("pmsFlowStatus__c");
        syncPmsBudgetToOpt.savePmsBudgetById(3864588692999463L, "0066F00001DXcArQAL", flowStatusPicks);
    }

    /**
     * 同步概算数据
     * @param type 1:初始化同步  2：增量同步
     */
    public void syncPmsBudget(int type) {
        try {
            LOGGER.info(LOGGER_MSG + "开始同步概算数据: " + type);
            // 获取满足条件的业务机会数据 获取项目阶段为售前  // pmsProjectCode__c 项目阶段  1：售前  2：交付  3：质保
            String sql = "select id,SF_ID__c from opportunity where pmsProjectCode__c is not null ";
            // 如果是增量只查询某段时间内有修改的数据
            SyncConfig__c syncConfig = new SyncConfig__c();
            if (type == 2) {
                sql += " and ProjectPhase__c = 1 ";

                // 获取开始实际、结束时间
                String configSql = "select id,lastSyncTime__c from syncConfig__c where syncKey__c = 'PMS_GS'";
                syncConfig = hcxObjectService.queryOne(configSql);
                String lastSyncTime = syncConfig.getLastSyncTime__c();
                Long endDateLong = System.currentTimeMillis(); // 同步结束时间
                if (lastSyncTime == null) {
                    lastSyncTime = HCDateUtils.getDaysBeforeLong(1).toString();
                }
                sql += String.format(" and updatedAt between %s and %s ", lastSyncTime, endDateLong);
            } else {
                // 初始化同步
                sql += " and ProjectPhase__c is not null ";
            }
            LOGGER.info(LOGGER_MSG + "sql: " + sql);

            List<JSONObject> opportunityList = xoqlService.query(sql).getRecords();
            syncConfig.setLastSyncCount__c(Long.valueOf(opportunityList.size()));
            LOGGER.info(LOGGER_MSG + "opportunityList: " + opportunityList.size());

            // 获取税率通用选项集
            JSONArray flowStatusPicks = ComUtils.getGlobalPicks("pmsFlowStatus__c");

            // 同步数据
            for (JSONObject opportunity : opportunityList) {
                savePmsBudgetById(opportunity.getLong("id"), opportunity.getString("SF_ID__c"), flowStatusPicks);
            }

            // 更新同步时间
            if (type == 2) {
                Long endDateLong = System.currentTimeMillis(); // 同步结束时间
                syncConfig.setLastSyncTime__c(endDateLong.toString());
                syncConfig.setSyncAssistVal__c(HCDateUtils.longToString(endDateLong, HCDateUtils.FORMATTIME));
                hcxObjectService.update(syncConfig);
            }

            LOGGER.info(LOGGER_MSG + "同步结束");
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.info(LOGGER_MSG + "同步异常: " + e.getMessage());
        }
    }


    /**
     * 同步PMS概算信息到业务机会以及概算模块 ()
     *
     * @param opportunityId
     * @param sfId
     * @param flowStatusPicks
     * @return
     */
    public ResultVo savePmsBudgetById(Long opportunityId, String sfId, JSONArray flowStatusPicks) {
        LOGGER.info(LOGGER_MSG + "开始处理");
        // 查询PMS概算信息
        try {
            // 根据业务机会获取PMS概算信息
            String optIds = opportunityId.toString();
            if (StringUtils.isNotBlank(sfId)) {
                optIds += "," + sfId;
            }
            LOGGER.info(LOGGER_MSG + "optIds: " + optIds);
            JSONObject response = PromotionApiUtil.getEstimateData(optIds);
            if (!Objects.equals(response.getInteger("code"),0)) {
                LOGGER.error(LOGGER_MSG + "查询机会PMS概算信息异常");
                return ResultVo.getFail("查询机会PMS概算信息异常:" + response.getString("msg"));
            }

            // 判断值是否正常
            JSONObject resData = response.getJSONObject("data");
            String preNo = resData.getString("preNo");
            LOGGER.debug(LOGGER_MSG + "preNo: " + preNo);
            if (StringUtils.isBlank(preNo)) {
                LOGGER.info(LOGGER_MSG + "当前机会在PMS没有提交或审批通过的概算");
                return ResultVo.getFail("当前机会在PMS没有提交或审批通过的概算");
            }

            // 获取概算详情列表
            List<JSONObject> preEstimateList = JSONArray.parseArray(resData.getString("preEstimateList"), JSONObject.class);
            if (preEstimateList == null) {
                return ResultVo.getFail("preEstimateList null");
            }
            LOGGER.debug(LOGGER_MSG + "preEstimateList:" + preEstimateList.size());

            // 根据产品编码获取到CRM产品id
            String productMaterialNos = preEstimateList.stream().map(v -> "'" + v.getString("productMaterialNo") + "'").collect(Collectors.joining(","));
            String sql = String.format("select id,productCode__c from product where productStatus__c = 1 and productCode__c in (%s)", productMaterialNos);
            Map<String, Long> crmProductMap = xoqlService.query(sql).getRecords().stream().collect(Collectors.toMap(e1 -> e1.getString("productCode__c"), e2 -> e2.getLong("id"), (e1, e2) -> e1));

            // 先删除之前保存的数据
            sql = "select id from detailEstimates__c where opportunityId__c = " + opportunityId;
            List<DetailEstimates__c> delList = hcxObjectService.query(sql, DetailEstimates__c.class);
            if (delList.size() > 0) {
                hcxObjectService.batchDelete(delList);
            }

            // 保存数据到  概算模块
            List<DetailEstimates__c> crmAddList = new ArrayList<>();
            for (int i = 0; i < preEstimateList.size(); i++) {
                JSONObject preEstimate = preEstimateList.get(i);
                DetailEstimates__c detailEstimates = new DetailEstimates__c();
                detailEstimates.setEntityType(3505414949968549L);
                detailEstimates.setName(String.valueOf(i + 1));
                detailEstimates.setOpportunityId__c(opportunityId);
                detailEstimates.setMaterialDescription__c(crmProductMap.get(preEstimate.getString("productMaterialNo"))); // 产品
                detailEstimates.setCPZJHS__c(preEstimate.getDouble("totalPriceTax")); // 总价含税
                detailEstimates.setCPZJBHS__c(preEstimate.getDouble("totalPrice")); // 总价不含税
                detailEstimates.setSL__c(preEstimate.getString("taxRate")); // 税率
                crmAddList.add(detailEstimates);
            }
            LOGGER.debug(LOGGER_MSG + "crmAddList:" + crmAddList.size());
            hcxObjectService.batchInsert(crmAddList);

            // 保存到业务机会 概算总金额、项目毛利
            Opportunity upOpportunity = new Opportunity();
            upOpportunity.setId(opportunityId);

            // 返点比列
            String rebate = resData.getString("rebate"); // 是否返点 返回 true || false
            upOpportunity.setIsReturnPoint__c(rebate == null ? null : Objects.equals("true", rebate) ? 1 : 2); // 是否返点 1: 是  2: 否
            upOpportunity.setRebateFee__c(resData.getDouble("rebateFee")); // 返点费用
            upOpportunity.setRebateRatio__c(resData.getDouble("rebateFeeRatio")); // 返点比列
            upOpportunity.setEstimatedAmount__c(resData.getDouble("taxIncludedAmount")); // 概算总金额 含税
            upOpportunity.setEstimatedNoTaxAmount__c__c(resData.getDouble("untaxedAmount")); // 概算总金额 不含税
            upOpportunity.setAttribute("pmsFlowStatus__c", ComUtils.getValueByApiKey(flowStatusPicks, resData.getString("currStatus")));  // 流程状态

            upOpportunity.setPmsBudgetSyncFlag__c("2"); // 同步状态
            JSONArray profitMeasurementList = resData.getJSONArray("profitMeasurementList");
            Object profitObj = profitMeasurementList.stream().filter(v -> {
                JSONObject object = (JSONObject) v;
                return object.getInteger("totalType") == 2;
            }).findFirst().orElse(null);
            if (profitObj != null) {
                JSONObject profitData = (JSONObject) profitObj;
                upOpportunity.setBudgetGrossProfit__c(profitData.getDouble("grossProfitCount")); // 项目毛利
                upOpportunity.setBudgetGrossProfitRate__c(profitData.getDouble("grossProfitMarginCount")); // 项目毛利率
            }
            hcxObjectService.update(upOpportunity);

            return ResultVo.getSuccess("处理成功");
        } catch (Exception e) {
            e.printStackTrace();
            return ResultVo.getFail("同步概算信息异常: " + e.getMessage());
        }
    }

}
